#include "fileTree.h"
#include "IOControlLayer.h"

void FileTree::insertDir(const std::string &str) {
    std::vector<std::string> parts = splitPath(str);
    FileTreeNode* node = _rootNode;
    std::string path = node->fileName;
    for (auto& part : parts) {
        if (!node->find(part)) {
            uint32_t idx = IOControlLayer::GetInstance().create_dir(path, node->inxde, part);
            // std::cout << "Insert " << path << " success" << std::endl;
            node->child[part] = new FileTreeNode(std::move(part), idx);
        }
        node = node->child[part];
        path += "/" + part;
    }
}

bool FileTree::insertFile(const std::string &str, const std::string &data){
    std::vector<std::string> parts = splitPath(str);
    FileTreeNode* node = _rootNode;
    std::string path = node->fileName;
    for (auto& part : parts) {
        if (!node->find(part)) {
            if (part != parts.back()){
                return false;
            }
            std::cout << "Insert " << part << " success" << std::endl;
            uint32_t idx = IOControlLayer::GetInstance().create_file(path, node->inxde, part, data);
            node->child[part] = new FileTreeNode(std::move(part), idx, false);
        }
        node = node->child[part];
        path += "/" + part;
    }
    return true;
}

void FileTree::insertInitialize(const std::string &str, uint32_t idx)
{
    std::vector<std::string> parts = splitPath(str);
    FileTreeNode* node = _rootNode;
    for (auto& part : parts) {
        if (!node->find(part)) {
            node->child[part] = new FileTreeNode(std::move(part), idx);
        }
        node = node->child[part];
    }
}

uint32_t FileTree::search(const std::string &str) {
    std::vector<std::string> parts = splitPath(str);
    FileTreeNode* node = _rootNode;
    for (auto& part : parts) {
        if (!node->find(part)) {
            return 0;
        }
        node = node->child[part];
    }
    return node->inxde;
}

void FileTree::print(const std::string &str) {
    std::vector<std::string> parts = splitPath(str);
    FileTreeNode* node = _rootNode;
    for (auto& part : parts) {
        if (!node->find(part)) {
            return;
        }
        node = node->child[part];
    }
    if (node->child.empty()) return;
    for (auto& child : node->child) {
        std::cout << child.first << " ";
    }
    std::cout << std::endl;
    return;
}

std::vector<std::string> FileTree::splitPath(const std::string &path) {
    std::vector<std::string> parts;
    std::istringstream iss(path);
    std::string part;

    // 以 '/' 为分隔符拆分字符串
    while (std::getline(iss, part, '/')) {
        if (!part.empty()) {
            parts.push_back(std::move(part));
        }
    }
    return parts;
}